# coding=utf-8
import logging
import os
import re
import uuid
from pathlib import Path
from urllib.parse import urlparse
import os

import requests

class CovertService:
    def download_images_and_convert_md(self,input_md_path, output_md_path=None, image_dir=None):
        """
        将 Markdown 文件中的图片链接转化为本地图片并保存为新文件

        参数:
            input_md_path (str): 输入的 Markdown 文件路径
            output_md_path (str, optional): 输出的 Markdown 文件路径，默认在原文件名后加 '_local'
            image_dir (str, optional): 图片存储目录，默认为 'images' 子目录
        """
        # 设置默认输出路径
        if output_md_path is None:
            base, ext = os.path.splitext(input_md_path)
            output_md_path = f"{base}_local{ext}"

        # 设置默认图片目录
        if image_dir is None:
            image_dir = os.path.join(os.path.dirname(output_md_path), "assert")

        # 确保图片目录存在
        Path(image_dir).mkdir(parents=True, exist_ok=True)

        # 读取原始 Markdown 文件
        with open(input_md_path, 'r', encoding='utf-8') as f:
            md_content = f.read()

        # 查找所有图片标记
        matches=self.extract_markdown_image_links(md_content)
        total = len(matches)
        index = 1
        # 处理每个图片
        for img_info in matches:
            img_url=img_info['url']
            alt_text=index
            logging.warning(f"{index}>>>download_images_and_convert_md>>>开始下载链接为:{img_url},task1:下载进度为{index * 100 / total}%")
            try:
                # 下载图片
                response = requests.get(img_url, stream=True, timeout=10)
                response.raise_for_status()

                # 确定文件扩展名
                parsed_url = urlparse(img_url)
                ext = os.path.splitext(parsed_url.path)[1]
                if not ext:
                    content_type = response.headers.get('content-type', '')
                    if 'jpeg' in content_type or 'jpg' in content_type:
                        ext = '.jpg'
                    elif 'png' in content_type:
                        ext = '.png'
                    elif 'gif' in content_type:
                        ext = '.gif'
                    else:
                        ext = '.jpg'  # 默认

                # 生成唯一文件名
                img_filename = f"{uuid.uuid4().hex}{ext}"
                local_img_path = os.path.join(image_dir, img_filename)

                # 保存图片
                with open(local_img_path, 'wb') as img_file:
                    for chunk in response.iter_content(1024):
                        img_file.write(chunk)

                # 在Markdown中替换URL为本地路径
                # 使用相对路径（相对于输出Markdown文件）
                rel_img_path = os.path.relpath(local_img_path, os.path.dirname(output_md_path))
                md_content = md_content.replace(
                    f"{img_info['text']}",
                    f"![{alt_text}]({rel_img_path})"
                )

            except Exception as e:
                print(f"无法下载图片 {img_url}: {str(e)}")
                continue
            logging.warning(f"{index}>>>download_images_and_convert_md>>>完成下载链接为:{img_url},task1:下载进度为{index * 100 / total}%")
            index+=1

        # 写入新的Markdown文件
        with open(output_md_path, 'w', encoding='utf-8') as f:
            f.write(md_content)

        print(f"转换完成！新文件已保存到: {output_md_path}")
        print(f"图片保存在: {image_dir}")

    def get_md_files(self,directory, recursive=False):
        """
        获取指定目录下的所有 .md 文件

        Args:
            directory (str): 目标目录
            recursive (bool): 是否递归查找子目录（默认 False）

        Returns:
            list: 所有匹配的 .md 文件路径列表（绝对路径）
        """
        md_files = []

        if recursive:
            # 递归遍历
            for root, _, files in os.walk(directory):
                for file in files:
                    if file.endswith(".md"):
                        md_files.append(os.path.join(root, file))
        else:
            # 只在当前目录查找
            for file in os.listdir(directory):
                if file.endswith(".md"):
                    md_files.append(os.path.join(directory, file))

        return md_files

    def extract_markdown_image_links(self,md_content):
        result=[]
        md_contents=md_content.split("\n")
        for line in md_contents:
            url=self.extract_markdown_image_link(line)
            if url!=None and len(url)>0:
                result.append(url)
        return result


    def convert_md(self,dir):
        files=self.get_md_files(directory=dir)
        for file in files:
            self.download_images_and_convert_md(file)

    def extract_markdown_image_link(self, line,patterns=None):
        match = re.search(r"(https?://)?[\w./-]+\.(?:png|jpg|jpeg|gif|webp)(?=\s|$|#)", line)
        if match:
            img_dict = dict()
            image_url = match.group(0)
            img_dict['url'] = image_url
            img_dict['text'] = line
            return img_dict
        match = re.search(r'!\[.*?\]\((https://[^\s)]+\.png)\)', line)
        if match:
            img_dict = dict()
            image_url = match.group(1)
            img_dict['url'] = image_url
            img_dict['text'] = line
            return img_dict





# 使用示例
if __name__ == "__main__":
    this=CovertService()
    dir = r"C:\Users\17812\PycharmProjects\craw\src\com\itheima\web\article"  # 替换为你的Markdown文件路径
    this.convert_md(dir)
    # img_str='![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/7247b0bd427653fe5a3a285de99ade77.png)'
    # match=this.extract_markdown_image_link(img_str)
    # print(match)